<template>
  <div class="container-wrapper">
    <div class="container mt-4">
      <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);" class="p-4 rounded">
        <h1 class="text-center mb-4 text-white">失物招领</h1>
        <p class="text-center mb-4 text-white">贡献者享受荣誉，失物者获得安心</p>
      </div>
      
      <!-- 搜索区域 -->
      <div class="search-container mb-4">
        <div class="row">
          <div class="col-md-4 mb-3">
            <div class="input-group search-group">
              <span class="input-group-text search-icon"><i class="bi bi-search"></i></span>
              <input type="text" class="form-control search-input" placeholder="搜索帖子标题、地点或内容..." v-model="searchKeyword">
            </div>
          </div>
          <div class="col-md-2 mb-3">
            <div class="input-group filter-group">
              <span class="input-group-text filter-icon"><i class="bi bi-tag"></i></span>
              <select class="form-select filter-select" v-model="selectedCategory">
                <option value="">全部分类</option>
                <option v-for="category in categories" :key="category.id" :value="category.id">
                  {{ category.name }}
                </option>
              </select>
            </div>
          </div>
          <div class="col-md-3 mb-3">
            <div class="input-group filter-group">
              <span class="input-group-text filter-icon"><i class="bi bi-calendar"></i></span>
              <select class="form-select filter-select" v-model="selectedTime">
                <option value="">全部时间</option>
                <option value="today">今天</option>
                <option value="3days">三天内</option>
                <option value="week">一周内</option>
                <option value="month">一个月内</option>
                <option value="halfYear">半年内</option>
                <option value="year">一年内</option>
              </select>
            </div>
          </div>
          <div class="col-md-3 mb-3">
            <div class="input-group filter-group">
              <span class="input-group-text filter-icon"><i class="bi bi-geo-alt"></i></span>
              <select class="form-select filter-select" v-model="selectedLocation">
                <option value="">全部地点</option>
                <option value="体育馆主馆">体育馆主馆</option>
                <option value="校西门停车场">校西门停车场</option>
                <option value="运动场">运动场</option>
                <option value="北校区公寓">北校区公寓</option>
                <option value="教学楼区域">教学楼区域</option>
                <option value="食堂">食堂</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- 物品列表 -->
      <div class="row items-wrapper" v-if="filteredItems.length > 0">
        <div class="col-md-6 col-lg-4 mb-4" v-for="item in filteredItems" :key="item.id">
          <div class="card item-card h-100">
            <img 
              :src="item.cover || defaultPostCover" 
              class="card-img-top" 
              :alt="item.title"
              @error="handleImageError"
              style="height: 200px; object-fit: cover;"
            >
            <div class="card-body">
              <h5 class="card-title">{{ item.title }}</h5>
              <div class="d-flex justify-content-between align-items-center mb-2">
                <span class="time-badge px-2 py-1 rounded">
                  <i class="bi bi-tag me-1"></i>{{ getCategoryName(item.itemTypeId ) }}
                </span>
                <span class="location-badge px-2 py-1 rounded">
                  <i class="bi bi-geo-alt me-1"></i> {{ item.location }}
                </span>
              </div>
              <p class="card-text">
                <strong>内容:</strong> {{ item.content }}
              </p>
              <p class="card-text">
                <strong>发布时间:</strong> {{ formatDate(item.createdAt) }}
              </p>
              <p class="card-text">
                <strong>浏览量:</strong> {{ item.viewCount }}
              </p>
              <div class="mt-3">
                <button class="btn btn-outline-primary btn-sm me-2" @click="contactPoster(item)">
                  <i class="bi bi-telephone me-1"></i>联系发布者
                </button>
                <button class="btn btn-outline-secondary btn-sm" @click="showDetail(item)">
                  <i class="bi bi-info-circle me-1"></i>详情
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div class="empty-state" v-else>
        <i class="bi bi-inbox"></i>
        <h4>没有找到相关物品</h4>
        <p>请尝试调整搜索条件或筛选条件</p>
      </div>

      <!-- 感谢信息 -->
      <div class="thank-you-section text-center my-5 py-4">
        <div class="thank-you-content">
          <i class="bi bi-heart-fill text-danger fs-1 mb-3"></i>
          <h3 class="mb-3">感谢您的帮助</h3>
          <p class="lead">让失物重新回到了原主身边</p>
          <div class="appreciation-text mt-3">
            <p>每一次善举都让校园更温暖</p>
          </div>
        </div>
      </div>
    </div>
    <BackToTop>
  </BackToTop>
</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import BackToTop from '@/components/BackToTop.vue'
import { getPostTypesService,
          getProductsListsService,
          getPostCoverByIdService,
          incrementPostViewCountService} from '@/api/post.js'
import defaultPostCover from '@/assets/images/封面加载失败.webp'

const searchKeyword = ref('')// 搜索关键词
const selectedCategory = ref('')// 分类筛选
const categories = ref([]) // 存储从后端获取的分类数据
const selectedTime = ref('')// 时间筛选
const selectedLocation = ref('')// 地点筛选
const items = ref([])// 物品数据


// 获取物品列表
const fetchItems = async () => {
  try {
    const res = await getProductsListsService({ categoryId: 1 })
    
    // 处理物品列表，添加封面图片和类别名称
    const itemsWithCovers = await Promise.all((res.data || []).map(async (item) => {
      try {
        const coverRes = await getPostCoverByIdService(item.id)
        let coverImage = defaultPostCover
        
        if (coverRes.data && coverRes.data.length > 0) {
          // 如果有封面图片，使用第一张图片
          const firstImage = coverRes.data[0]
          coverImage = firstImage.imageUrl.startsWith('http') 
            ? firstImage.imageUrl 
            : `http://localhost:8080${firstImage.imageUrl}`
        }
        
        return {
          ...item,
          cover: coverImage
        }
      } catch (error) {
        console.error(`获取物品 ${item.id} 的封面失败:`, error)
        // 如果获取图片失败，使用默认图片
        return {
          ...item,
          cover: defaultPostCover
        }
      }
    }))
    
    items.value = itemsWithCovers
    console.log("物品列表:", items.value)
  } catch (error) {
    console.error("获取物品列表失败:", error)
    items.value = []
  }
}

// 根据类别ID获取类别名称
const getCategoryName = (categoryId) => {
  // 如果没有categoryId，则返回默认值"其他"
  if (!categoryId) return '其他'
  if (!categories.value || categories.value.length === 0) return categoryId
  
  // 查找匹配的分类
  const category = categories.value.find(cat => {
    // 尝试多种可能的ID字段
    return cat.id == categoryId || cat.categoryId == categoryId || cat.itemTypeId == categoryId
  })
  
  // 返回分类名称或原始ID
  return category ? (category.name || category.title || category.label || categoryId) : `分类${categoryId}`
}

// 计算属性：筛选后的物品列表
const filteredItems = computed(() => {
  return items.value.filter(item => {
    // 分类筛选
    if (selectedCategory.value) {
      return item.itemTypeId == selectedCategory.value
    }
   
    
    // 时间筛选
    if (selectedTime.value) {
      const now = new Date()
      // 统一使用 createdAt 字段作为发布时间
      const itemDate = new Date(item.createdAt || item.time)
      const timeDiff = now.getTime() - itemDate.getTime()
      const daysDiff = timeDiff / (1000 * 3600 * 24)
      
      switch(selectedTime.value) {
        case 'today':
          if (daysDiff > 1) return false
          break
        case '3days':
          if (daysDiff > 3) return false
          break
        case 'week':
          if (daysDiff > 7) return false
          break
        case 'month':
          if (daysDiff > 30) return false
          break
        case 'halfYear':
          if (daysDiff > 180) return false
          break
        case 'year':
          if (daysDiff > 365) return false
          break
      }
    }
    
    // 地点筛选
    if (selectedLocation.value && item.location !== selectedLocation.value) {
      return false
    }
    
    // 关键词搜索
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase().trim()
      return (
        (item.title && item.title.toLowerCase().includes(keyword)) ||
        (item.location && item.location.toLowerCase().includes(keyword)) ||
        (item.lostLocation && item.lostLocation.toLowerCase().includes(keyword)) ||
        (item.content && item.content.toLowerCase().includes(keyword))
      )
    }
    
    return true
  })
})

// 物品详情
const showDetail = (item) => {
  // 增加浏览量
  incrementPostViewCountService(item.id).then(() => {
    // 浏览量增加成功后，更新数据
    item.viewCount = (item.viewCount || 0) + 1
  })
  // 跳转到商品详情页--window.open新创建一个窗口
  window.open(`/post/detail/${item.id}`);
}

// 联系发布者
const contactPoster = (item) => {
  alert(`正在联系发布者: ${item.contact}`)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = defaultPostCover
}

onMounted(() => {
  // 获取分类
  getPostTypesService(1).then(res => {
    categories.value = res.data
    console.log("分类数据:", res.data)
  })
  // 获取物品列表
  fetchItems()
})
</script>

<style scoped>
.container-wrapper {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  min-height: 100vh;
  padding: 20px 0;
}

.search-container {
  background: linear-gradient(to right, #f8f9fa, #e9ecef);
  border-radius: 15px;
  padding: 25px;
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
  border: 1px solid rgba(0,0,0,0.05);
}

.search-group,
.filter-group {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  border: none;
  transition: all 0.3s ease;
}

.search-group:hover,
.filter-group:hover {
  box-shadow: 0 4px 15px rgba(0,0,0,0.15);
  transform: translateY(-2px);
}

.search-icon,
.filter-icon {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 12px 0 0 12px;
  font-weight: bold;
}

.search-input,
.filter-select {
  border: none;
  padding: 12px 15px;
  box-shadow: none;
  border-radius: 0 12px 12px 0;
  height: 100%;
  background-color: white;
}

.search-input:focus,
.filter-select:focus {
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
  outline: none;
  border-radius: 0 12px 12px 0;
}

.filter-btn {
  border-radius: 20px;
  margin-right: 8px;
  margin-bottom: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

.filter-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0,0,0,0.15);
}

.time-badge {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  font-size: 0.8rem;
  border-radius: 20px;
  padding: 5px 10px;
}

.location-badge {
  background: linear-gradient(135deg, #34c759, #2c7a4d);
  color: white;
  font-size: 0.8rem;
  border-radius: 20px;
  padding: 5px 10px;
}

.card-text {
  color: #6c757d;
  font-size: 0.9rem;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 0.5rem;
  min-height: 2.4rem; /* 设置最小高度确保至少两行 */
}

.items-wrapper {
  min-height: 600px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #6c757d;
  background: linear-gradient(to bottom, #f8f9fa, #e9ecef);
  border-radius: 15px;
  margin: 20px;
  min-height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.thank-you-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 15px;
  color: white;
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

.thank-you-content {
  max-width: 600px;
  margin: 0 auto;
  padding: 2rem;
}

.thank-you-content h3 {
  font-weight: 600;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.2);
}

.thank-you-content .lead {
  font-size: 1.2rem;
  opacity: 0.9;
}

.thank-you-content .appreciation-text p {
  font-style: italic;
  margin: 0;
  opacity: 0.8;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 15px;
  color: #dee2e6;
}

.card-title {
  color: #343a40;
  font-weight: 600;
  font-size: 1.2rem;
}

.card-text {
  color: #6c757d;
  font-size: 0.9rem;
}

.item-card {
  transition: all 0.3s ease;
  cursor: pointer;
  border-radius: 15px;
  overflow: hidden;
  height: 100%;
  border: none;
  background: linear-gradient(to bottom, #ffffff, #f8f9fa);
  box-shadow: 0 4px 15px rgba(0,0,0,0.08);
}

.item-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0,0,0,0.15);
}

/* 标题样式 */
h1 {
  color: white;
  text-shadow: 1px 1px 3px rgba(0,0,0,0.3);
}

/* 副标题样式 */
p.text-center.mb-4 {
  color: #f8f9fa;
  font-size: 1.1rem;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.2);
}
</style>